<template>
    <el-upload
        class="upload-demo"
        action=""
        :on-change="handleChange"
        :on-remove="handleRemove"
        :on-exceed="handleExceed"
        :limit="3"
        :multiple="true"
        accept="application/vnd.openxmlformats-
        officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
        :auto-upload="false">
    <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
</template>
<script>
import * as fs from 'fs'
import { saveAs } from 'file-saver'

export default {
    name: 'T5',
    data() {
        return {
            key: '',
        }
    },
    methods: {
        getWater(outdata) {
            let abdWater = []
            for (let k = 1; k <= 39 * 6 + 2; k += 39) {
                let sum = 0
                let len = k + 3
                for (let j = len; j < len + 36; j++) {
                    sum += outdata[j].__EMPTY_8
                }
                abdWater.push({
                    name: outdata[k][this.key].split('：')[1],
                    value: sum,
                })
                // 求水位、出库流量、入库流量、出力
                // wls[`${outdata[k]['1245.05']}`] = waterLevel
                // int[`${outdata[k]['1245.05']}`] = inboundTraffic
                // out[`${outdata[k]['1245.05']}`] = outboundTraffic
                // con[`${outdata[k]['1245.05']}`] = contribute
            }
            return abdWater
        },
        // 求其他四个值
        getFourData(outdata) {
            let waterLevel = []
            let inboundTraffic = []
            let outboundTraffic = []
            let contribute = []
            for (let k = 1; k <= 39 * 6 + 2; k += 39) {
                let arr = []
                let arr1 = []
                let arr2 = []
                let arr3 = []
                let len = k + 3
                for (let j = len; j < len + 36; j++) {
                    arr.push(outdata[j].__EMPTY)
                    arr1.push(outdata[j].__EMPTY_5)
                    arr2.push(outdata[j].__EMPTY_6)
                    arr3.push(outdata[j].__EMPTY_9)
                }
                waterLevel.push({
                    name: outdata[k][this.key].split('：')[1],
                    data: arr,
                })
                inboundTraffic.push({
                    name: outdata[k][this.key].split('：')[1],
                    data: arr1,
                })
                outboundTraffic.push({
                    name: outdata[k][this.key].split('：')[1],
                    data: arr2,
                })
                contribute.push({
                    name: outdata[k][this.key].split('：')[1],
                    data: arr3,
                })
            }
            return { waterLevel, inboundTraffic, outboundTraffic, contribute }
        },

        handleChange(file, fileList) {
            this.fileTemp = file.raw
            if (this.fileTemp) {
                if ((this.fileTemp.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
                    || (this.fileTemp.type == 'application/vnd.ms-excel')) {
                    this.importfxx(this.fileTemp)
                } else {
                    this.$message({
                        type: 'warning',
                        message: '附件格式错误，请删除后重新上传！',
                    })
                }
            } else {
                this.$message({
                    type: 'warning',
                    message: '请上传附件！',
                })
            }
        },
        fixdata(data) {
            // 文件流转BinaryString
            let o = '',
                l = 0,
                w = 10240
            for (; l < data.byteLength / w; ++l) {
                o += String.fromCharCode.apply(null,
                    new Uint8Array(data.slice(l * w, l * w + w)))
            }
            o += String.fromCharCode.apply(null,
                new Uint8Array(data.slice(l * w)))
            return o
        },
        importfxx(obj) {
            let that = this
            let inputDOM = this.$refs.inputer
            // 通过DOM取文件数据

            // eslint-disable-next-line no-restricted-globals
            this.file = event.currentTarget.files[0]

            let rABS = false // 是否将文件读取为二进制字符串
            let f = this.file

            let reader = new FileReader()
            // if (!FileReader.prototype.readAsBinaryString) {
            FileReader.prototype.readAsBinaryString = function (f) {
                let binary = ''
                let rABS = false // 是否将文件读取为二进制字符串
                let pt = this
                let wb // 读取完成的数据
                let outdata
                let reader = new FileReader()
                // eslint-disable-next-line func-names
                reader.onload = function (e) {
                    let bytes = new Uint8Array(reader.result)
                    let length = bytes.byteLength
                    for (let i = 0; i < length; i++) {
                        binary += String.fromCharCode(bytes[i])
                    }
                    // 此处引入，用于解析excel
                    let XLSX = require('xlsx')
                    if (rABS) {
                        wb = XLSX.read(btoa(this.fixdata(binary)), {
                        // 手动转化
                            type: 'base64',
                        })
                    } else {
                        wb = XLSX.read(binary, {
                            type: 'binary',
                        })
                    }
                    outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
                    that.key = Object.keys(outdata[0])[0]
                    let abdWater = that.getWater(outdata)
                    let { waterLevel, inboundTraffic, outboundTraffic, contribute } = that.getFourData(outdata)
                    // outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
                    // 此处可对数据进行处理
                    /* eslint no-underscore-dangle: 0 */
                    // 分别为总发电量、总弃水量、水位、入库流量、出库流量、弃水流量、出力
                    // 求的是一年的总水量
                    let totalPower = []
                    for (let j = 1; j <= 39 * 6 + 2; j += 39) {
                        totalPower.push({
                            name: outdata[j][that.key].split('：')[1],
                            value: parseFloat(outdata[j + 1][that.key].split('：')[1]),
                        })
                    }
                    let data = {
                        2009: {
                            totalPower,
                            abdWater,
                            waterLevel,
                            inboundTraffic,
                            outboundTraffic,
                            contribute,
                        },
                    }
                    // 读写文件json
                    let content = JSON.stringify(data)
                    let blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
                    saveAs(blob, 'save1.json')
                    that.da = totalPower
                    that.dalen = totalPower.length
                    return data
                }
                reader.readAsArrayBuffer(f)
            }
            if (rABS) {
                reader.readAsArrayBuffer(f)
            } else {
                reader.readAsBinaryString(f)
            }
        },
    },
}
</script>